home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / Libraries / VideoToolbox 96.06.15 / VideoToolboxSources / SetEntriesQuickly.c < prev    next >
Text File  |  1996-03-05  |  51KB  |  1,322 lines

  1. /*
  2. SetEntriesQuickly.c
  3.  
  4. SetEntriesQuickly loads your video card’s clut as quickly as possible.
  5.  
  6. SetEntriesQuickly was written by many people, and the “final” result has not
  7. been tested on all the computers and video devices it’s meant to support. The
  8. best test is simply to run TimeVideo, which gives it a thorough workout on all
  9. of your computer’s video devices. Please send the report “TimeVideo results” to
  10. denis@xp.psych.nyu.edu, and I’ll add your test results to “Video bugs” and the
  11. following list.
  12.  
  13. VIDEO DEVICES CERTIFIED by TimeVideo as compatible with SetEntriesQuickly():
  14. 1. Ok:
  15. “Macintosh Display Card 8•24 GC” (.Display_Video_Apple_MDCGC)
  16. Quadra 900 “Macintosh C Built-In Video” (only tested in 1,2,4,8-bit modes)
  17. Quadra 950 “Macintosh G Built-In Video” (only tested in 1,2,4,8,16-bit modes)
  18.  
  19. 2. Ok when loading whole clut at once, but fail read-back test when loading one 
  20. entry at a time (at least on the Quadra 840av). Bug reported by Ken Alexander 
  21. <U12940@UICVM.BITNET> and Wei Xie. This problem does not occur on most Macs.
  22. Apple 8•24 "Macintosh Display Card" (.Display_Video_Apple_MDC version 272)
  23.  
  24. 3. Ok, except for visible hash (dynamic black specks) during clut loading:
  25. Apple “Mac II High-Resolution Video Card” (.Display_Video_Apple_HRVC)
  26. Apple “Toby frame buffer card” (.Display_Video_Apple_TFB version 5)
  27. Mac IIci “Macintosh II Built-In Video” (.Display_Video_Apple_RBV1)
  28.  
  29. 4. Don't work (hopefully will be fixed soon):
  30. RasterOps “ProColor 32” (.RasterOps 1.0 32XL Video Driver version 9327)
  31.  
  32. CONTRIBUTORS TO THIS LIST
  33. Ken Alexander <U12940@UICVM.BITNET> (bug in SetEntriesQuickly)
  34. Kyle Cave, cavekr@ctrvax.vanderbilt.edu (Quadra 700)
  35. Wei Xie (bug in SetEntriesQuickly for Apple 8•24 in Quadra 840AV)
  36.  
  37. Some Macintosh video drivers are poorly written; they take too long (more than a
  38. frame time) to load the clut. This is makes it impossible to do clut animation
  39. for temporal modulation etc., for which one needs to be able to reload the clut
  40. on each frame. At one time, many of us thought that the limitation was in
  41. hardware, in the RAMDAC, but we were wrong. Raynald Comptois disassembled
  42. several video drivers and wrote his own programs to load the clut quickly, and
  43. his programs manage to do it within a frame. Raynald was kind enough to share
  44. his code with me. I passed it on to Peter Lennie and Bill Haake, who polished
  45. it, making it compatible with the 68040 processor, and added support for more
  46. cards. I polished their work, made the routines self contained, adding a
  47. “device” argument to allow use in Macs that have more than one video device, and
  48. quickly figuring out all the key parameters (mode, pixelSize, DAC size, and clut
  49. size). There are now two alternative front ends: SetEntriesQuickly() for new
  50. users, and macltset() for backward compatibility with programs that used
  51. Raynald’s original routines. This modularity has increased run time only
  52. slightly, a fraction of a millisecond.
  53.  
  54. New drivers are hard to write, since they must directly address the registers of
  55. the video card, which are unique to each video card and undocumented. So the
  56. author of a driver must disassemble the original video driver and figure things
  57. out on his or her own. A lot of work.
  58.  
  59. SetEntriesQuickly is unlike the standard video drivers in the following ways:
  60. 1. SetEntriesQuickly always takes less than 2 ms to load the whole clut. 
  61. Some video drivers, e.g. for Apple’s 8•24 card, take several frames (>30 ms) to 
  62. finish loading the clut.
  63. 2A. SetEntriesQuickly does not wait for VBL, so a visible glitch may appear on
  64. the current frame, at least on some older video cards (e.g. Hi-Res, Toby, and
  65. Mac IIci). (You can prevent this glitch by calling SetEntriesQuickly only at
  66. blanking time. Use a VBL task or WaitForBlanking().) Newer cards and computers
  67. seem to have dual ported video clut memory so you can write at any point in the
  68. frame cycle without noticeable glitch, though of course you may want to synch
  69. the update for other reasons.
  70. 2B. A flag argument “waitForNextBlanking” is provided, but at present this
  71. option is only supported for the Toby video card.
  72. 3. SetEntriesQuickly ignores the gamma table, yielding the same result as using
  73. the standard video driver with an uncorrected gamma table. E.g. after calling
  74. GDUncorrectedGamma(device).
  75. 4. SetEntriesQuickly() does nothing and returns an error if the arguments
  76. specify loading of an out-of-range index. 
  77. 5. SetEntriesQuickly() does nothing and returns an error if the “count”
  78. specifies zero entries. This is contrary to the (bizarre) Apple convention that
  79. a cscSetEntries control call with a count corresponding to zero entries will result
  80. in loading of entries specified by the “value” field of the ColorSpec.
  81. 6. SetEntriesQuickly does not have immediate access to the video driver’s
  82. private tables. Therefore the first time you call SetEntriesQuickly() for a 
  83. particular device there is an extra delay of about 1 ms while some key
  84. information is ferreted out. That information is cached, so subsequent calls
  85. for the same device will be fast, spending most of their time loading the clut.
  86.  
  87. Two front ends are provided, for compatibility with two distinct traditions:
  88.  
  89. OSErr SetEntriesQuickly(GDHandle device,short start,short count,ColorSpec *table);
  90.  
  91. SetEntriesQuickly() uses the same calling convention as the VideoToolbox routine
  92. GDSetEntries() and, except for adding the GDHandle argument to specify the
  93. device, is also the same as Apple’s SetEntries() Color Manager routine,
  94. documented in Inside Macintosh V-143. Apple specifies special behavior when
  95. count==-1, but we don’t support that here and simply return with an error. I
  96. suggest that new users use SetEntriesQuickly rather that macltset. “start” is
  97. the index of the first clut entry to load, and should be greater than or equal
  98. to zero. “count” is the number of entries to load, minus 1. (Yes, “minus 1”,
  99. that’s Apple’s confusing convention.) “table” is a Colorspec array. (Each ColorSpec
  100. element is a structure consisting of a two-byte “value”, which is not used, and
  101. a 6-byte “rgb”, which, in turn is a structure of three 16-bit unsigned short
  102. ints: red, green, and blue. Apple’s convention is that the MOST SIGNIFICANT BITS
  103. of the 16-bit color values are used. It’s good practice in your programs to
  104. provide full 16-bit values, so that when you upgrade to fancier video cards with
  105. more-than-eight bit DACs your programs will benefit from the extra precision
  106. without needing any change. Returns zero if successful, nonzero if unsuccessful,
  107. i.e. illegal arguments.
  108.  
  109. short macltset(GDHandle device,short start
  110.     ,unsigned short* red,unsigned short* green,unsigned short* blue,short count1);
  111.  
  112. macltset() uses a calling convention established by Raynald Comtois, and
  113. provides backward compatibility with older programs. “red”, “green”, and “blue”
  114. are arrays of 16-bit unsigned short ints, of which the LEAST SIGNIFICANT BITS
  115. are used. “start” is the index of the first entry to change. “count1” is the
  116. number of entries to change (contrary to Apple’s convention).
  117.  
  118. Both front ends use the same general-purpose subroutine: LoadClut(), which in
  119. turn calls the hardware-specific routine appropriate to the particular video 
  120. device being used.
  121.  
  122. The useMostSignificantBits bit of the “flags” argument specifies whether to use 
  123. Apple’s convention (for users of SetEntriesQuickly) or Raynald’s convention 
  124. (for users of macltset).
  125.  
  126. At the moment all the supported video cards have 8-bit DACs, except the RasterOps
  127. ProColor 32, which has 9-bit DACs. If the useMostSignificantBits flag is true
  128. then you don’t need to worry, as the least significant bit of the 9-bit DAC
  129. simply picks up the next lower bit from your numbers, giving you a tad more
  130. precision. However, if useMostSignificantBits flag is false then, in order to
  131. use the full range of the DAC you must make all your numbers twice as big, or --
  132. cludge time! -- set the useOnly8Bits flag, to request that your 8-bit numbers be
  133. multiplied by two, allowing you to use the whole range of the DAC without
  134. changing the rest of your program, but wasting the DAC’s least significant bit
  135. by setting it permanently to zero.
  136.  
  137. SUSPENDING INTERRUPTS. If you wish, the low-level routines will suspend
  138. interrupts while loading the clut. Presumably Raynald had his reasons for
  139. implementing this, so this “feature” is enabled when you use macltset(). Peter
  140. Lennie writes, “The switch to uninterruptable processing during the write is, I
  141. think, out of the original drivers (though I’m not absolutely sure).  I imagine
  142. it’s to avoid display glitches that would result from some higher priority
  143. interrupt suspending a clut rewrite somewhere in the middle.” However, I (dgp)
  144. don’t see any advantage to suspending interrupts, and believe that there is a
  145. significant downside if you are trying to keep track of the VBL interrupts on
  146. several video cards, since suspending interrupts for 1 or 2 ms might be long
  147. enough to miss a whole VBL interval. Thus SetEntriesQuickly disables this
  148. “feature”. However, this is not a philosophical debate. We all agree that
  149. interrupts should be suspended if doing otherwise would occasionally result in a
  150. visible glitch. Does anyone know?
  151.  
  152. OSErr WaitForNextBlanking(GDHandle device);
  153.  
  154. Waits for beginning of next blanking interval. Currently this supports only the
  155. Toby and HiRes cards (Apple’s original video cards, now obsolete).
  156.  
  157. SPEED. SetEntriesQuickly() is self contained. You simply give it the GDHandle of
  158. your video device (as returned, e.g. by GetScreenDevice), and tell it what you
  159. want to do to the clut. In order to do this for you it needs to figure out a
  160. bunch of stuff about your video device. This research takes time; the first time
  161. you call it for a particular device it takes on the order of 1 ms to look up
  162. stuff. However, it saves this info in a cache, for each device, for quick
  163. retrieval on subsequent occasions. The implication is that programs that use
  164. SetEntriesQuickly ought to call it once just for practice (to get the cache
  165. loading over with) before using it in a situation where speed matters.
  166.  
  167. The coding of the LoadClut “driver” routines is a compromise between the needs
  168. of SetEntriesQuickly and macltset, which both use them. I decided not to write
  169. separate clut loading loops for the two cases (use most- vs. least-significant
  170. bits). I believe (but have not tested) that adding a register offset instead of
  171. using an autoincrement instruction incurs essentially no time penalty because
  172. the processor automatically overlaps the execution of such instructions. So I
  173. think that SetEntriesQuickly is running flat out, and don’t see any prospect of
  174. speeding it up significantly. On the other hand, I suspect that fetching the
  175. least significant byte by doing a byte access to an odd address (for macltset)
  176. does slow things down perhaps 30% (though I haven’t timed it) over doing a word
  177. access to an even address, as Raynald had originally coded it. If that speed
  178. loss is unacceptable, then one could insert an if(flags&useMostSignificantBits)
  179. statement into the relevant subroutine and write two separate loops optimized
  180. for the two cases. My guess is that the current compromise will be acceptable to
  181. all users.
  182.  
  183. A NOTE ON SPEED FROM DAVID BRAINARD:
  184. We have been looking pretty closely at video timing.  In our hands,
  185. SetEntriesQuickly does not always succeed in writing the CLUT during the
  186. vertical blank interval.  In particular, with the Apple 8-24 board on a IIfx
  187. running in the 800 by 600 mode at 75 Hz, it is a little too slow.  This causes a
  188. visible glitch at the top of the screen.  Whether it is fast enough is probably
  189. very hardware-configuration dependent, but it might be worth emphasizing in the
  190. documentation that use is caveat emptor.  You give < 2 ms as the write time,
  191. which is roughly correct, but not always fast enough. I may end up writing an
  192. assembler version to see if I can push it by 25%, which is about what I need.
  193. [However, assembly code won't be compatible with the Power PC.-dgp]
  194.  
  195. IMPROVEMENTS:
  196. It is hoped that others will add to the functionality of this routine. Please
  197. share your enhancements with others by sending them to denis@xp.psych.nyu.edu
  198. for inclusion in the VideoToolbox.
  199.  
  200. Those wishing to support new video devices should begin by buying and reading
  201. Apple’s Designing Cards and Drivers, 3rd Ed., Addison-Wesley, and then use the
  202. VideoToolbox utility GetVideoDrivers to copy all your drivers into resource
  203. files, and use ResEdit with CODE editor to peruse them. The ResEdit CODE editor
  204. is a public domain file distributed by:
  205. Ira L. Ruben
  206. Apple Computer, Inc.
  207. 20525 Mariani Ave., MS: 37-A
  208. Cupertino, Ca. 95014
  209. Ira@Apple.Com
  210. ftp://ftp.apple.com/dts/mac/tools/resedit/resedit-2-1-code-editor...
  211.  
  212. By the way, assembly code is hard to write, read, and maintain,
  213. and the speed advantage is negligible, about 10%. I suggest that
  214. all new code be written in C.
  215.  
  216. It is logical that we identify the video card by the card name,
  217. GDCardName(driver), but in fact getting the card name is very slow (1.5 ms)
  218. whereas getting the driver name is fast, GDName(driver), and would be
  219. sufficiently unique for our purposes. (E.g. the Toby and TFB video cards have
  220. the same driver, and our code works for both cards.) 
  221.  
  222. KNOWN BUGS:
  223. Has not been tested on all the video devices that are supposed to be supported.
  224. Please run the demo TimeVideo, and send the results file to denis@xp.psych.nyu.edu
  225.  
  226. Does not work with the RasterOps ProColor 32. Hopefully this will be fixed soon.
  227.  
  228. The Quadra code requires that start==0. (Apparently the same problem occurs when
  229. running the 8•24 card on a Quadra 840AV.) This could probably be figured out and
  230. fixed pretty easily if someone took the time to do so.
  231.  
  232. I recommend using the standard drivers (i.e. GDSetEntries/GDDirectSetEntries)
  233. instead of SetEntriesQuickly for the Toby and High Resolution video cards and
  234. the Mac IIci built-in video. Those standard drivers work fine, whereas for those
  235. devices SetEntriesQuickly produces visible dynamic black specks as it accesses
  236. the clut.
  237.  
  238. None of these routines wait for the vertical blanking interval before loading
  239. the clut. On older video devices--Toby, HiRes, Mac IIci--this results in visible
  240. dynamic black specks on the screen. I (dgp) consider this a bug, but, for most
  241. of these devices I don’t know how to wait for the end of frame, short of setting
  242. up an interrupt. (Just about every video card has a bit that one could monitor,
  243. but its address is usually undocumented.) Newer devices seem to be ok, because of
  244. dual-ported RAMDAC memory. Check this out on your devices by running TimeVideo.
  245.  
  246. QUADRA 660AV & 840AV
  247. Ben Singer, bens@swift.cvs.rochester.edu, writes,
  248. "I thought this information would prove useful to anyone using VideoToolbox on a
  249. 660AV or 840AV (the machines' video drivers are identical). It's possible to
  250. load the clut on 660/840AV's using the following code information:
  251.  
  252. INITIALIZATION INFO: 
  253.  
  254. slot id's for slot 0 (internal video):
  255.  
  256. quadra660 = 0x50; // quadra 660AV internal video
  257. quadra840 = 0x3D; // quadra 840AV internal video
  258.  
  259. driver name in each case is ".Display_Video_Apple_Civic"
  260. card name for 660AV is "Macintosh 3B"
  261. card name for 840AV is "Macintosh 3A"
  262.  
  263. CARDBASE INFO:
  264.  
  265. case quadra660:
  266. case quadra840:
  267.    {    
  268.     asm {
  269.         move.l 0xDD8,a0        // internal video 040 AV's
  270.         adda.l (a0),a0
  271.         move.l 164(a0),a1
  272.         move.l a1,cardBase
  273.     }
  274.     break;
  275.    }
  276.  
  277. LOADCLUT INFO:
  278.  
  279. case quadra660:
  280. case quadra840:
  281.    {
  282.     asm {    // no _SwapMMUMode; 040 AV's always in 32-bit mode
  283.         move.l cardBase,a1  
  284.         lea 0x10(a1),a1    // offsets 0x10,0x110,0x210,0x310 work
  285.         clr.l -16(a1)
  286.         move sr,-(a7)
  287.         ori #0x700,sr    // disable interrupts
  288.         subq.l #1,count // may want to take this out for VidTB
  289.         clr.l d1
  290.     @1    move.w (red)+,d1
  291.         move.b d1,(a1)
  292.         move.w (green)+,d1
  293.         move.b d1,(a1)
  294.         move.w (blue)+,d1
  295.         move.b d1,(a1)
  296.         clr.b (a1)
  297.         dbf count,@1
  298.         move (a7)+,sr    // enable interrupts
  299.     }
  300.    }
  301.    break;
  302.  
  303. I've tested this on both the 660AV and 840AV, but only in 8-bit ("256
  304. colors";count=256) mode. As with other quadra internal video code, this doesn't
  305. incorporate the "start" parameter. Thanks to Peter Lennie. Thanks also to you
  306. for GrabDriver and the tip on using the ResEdit CODE extension to examine the
  307. disassembly.
  308.  
  309. Ben Singer
  310. Postdoc, Center for Visual Science
  311. University of Rochester
  312. bens@swift.cvs.rochester.edu (Ben Singer)
  313.  
  314. RASTEROPS 8L & 24L:
  315. Rhea Eskew, eskew@neu.edu, writes "I use a RasterOps 8L board (it's probably
  316. obsolete now), which has one of those lousy drivers. However, RasterOps was nice
  317. enough to provide me with the register address and the blanking bit address, so
  318. I write directly to the hardware. The RasterOps 8L is the same as the 24L, just
  319. less memory. So I presume the register addresses are the same for the two
  320. boards. The board's base address is Fx000000, where x=Nubus slot number. The
  321. CLUT offset is FA0000. The vertical blanking bit is at offset F70000. Wait for
  322. bits 1 and 2 to both go high, then low. Ignore bit 0.
  323.      Here is the 680x0 assembly code that I use to write directly to the hardware of
  324. my RasterOps 8L board, to fill the clut. It's based on some asm supplied by
  325. RasterOps. Because I use FORTH, the opcode conventions shown below look a bit
  326. different from conventional 680x0 opcodes, but of course they do the same
  327. things. I think they could be figured out pretty easily (and I'm available if
  328. someone wants help)."
  329. hex                         \ everything's in hex
  330. FC000000 constant Cardbase    \ my card is in slot C -- the base address is
  331.                             \ Fx000000; substitute your hex slot # for x
  332. CardBase FA0000 + constant ClutBase        \ RasterOps-supplied offset
  333. CardBASE F70000    + constant VertBitOff    \ offset to vertical blanking register
  334. \ This is a FORTH code routine -- takes as stack-input parameters the listed
  335. \ numbers with VertBitOff on top of stack.
  336. \ ClutBase is base addr of rasterops board (FCA0000 for slot C)+Clutoffset (00FA0000)
  337. \ Sourceaddr is base address in RAM of the ColorSpecs (index,red,green,blue).
  338. \ count is number'of'em. (The clut data are stored as WORDS not bytes.)
  339. \ VertBitOff is register for vertical blanking (RObase+F70000)
  340. \ 'sp' stands for stack pointer = register a7
  341. \ (This version seems to work w/o glitches -- moved blanking up to top of routine.)
  342. code    R-OSetPal ( ClutBase\Sourceaddr\count\VertBitOff -- )
  343.     1  D0 MOVEQ, A05D w,    \ swappmmumode to 32bit
  344.     a4    d3    long    move,    \ save UP (a4) in d3; restore at end!
  345.     sp )+ a4    long move,    \ put vertbitoff into a4 
  346.     \ wait for blanking
  347.     begin,
  348.         a4 ()   1D 2    d1    bfextu,    \ offset is 29=$1D, bits 2 and 1 (bit 0 not used!!!)
  349.         d1    3      byte subq,    \ 3 equals 2 bits set at low end of d1
  350.     eq        until,            \ wait until it equals 3
  351.     begin,
  352.         a4 ()   1D 2    d1    bfextu,    \ offset is 29=$1D bits 2 and 1 (bit 0 not used!!!)
  353.     eq        until,            \ wait until both bits are zero
  354.     \ blanking done
  355.     sp )+ D0 long move,        \ put count to d0
  356.     sp )+ a1 long move,        \ put source into a1
  357.     sp )+ A0    long move,    \ put destination (clutbase) to a0
  358.     begin,
  359.         a1 )+ 3 a0  i) byte move,    \ index 
  360.         a1    1           long    ADDQ,    \ increment an extra byte
  361.         a1 )+ 7 a0  i) byte move,    \ red
  362.         a1    1           long    ADDQ,    \ increment an extra byte
  363.         a1 )+ 7 a0  i) byte move,    \ green
  364.         a1    1           long    ADDQ,    \ increment an extra byte
  365.         a1 )+ 7 a0  i) byte move,    \ blue
  366.         a1    1           long    ADDQ,    \ increment an extra byte
  367.         d0 1 long subq,
  368.     eq until,       
  369.     d3    a4    long move,        \ Restore UP
  370.     0  D0 MOVEQ, A05D w,    \ SwapMMUMode back
  371.     next
  372. end-code
  373.  
  374. HISTORY:
  375. 8/24/92 Original setcardbase and macltset provided by Raynald Comtois
  376. (raco@wjh12.harvard.edu) to Denis Pelli.
  377.  
  378. 10/2/92 Bill Haake added code for the RasterOps ProColor 32, which has 9-bit
  379. DACs and 9-bit entries in the lookup table.
  380.  
  381. 10/1/92 Peter Lennie added code for Quadra internal video.  No provision for
  382. changing the start position in the table, (I couldn't find any relevant
  383. disassembly) so 'start' is ignored, and you should write the whole table.
  384.     
  385. 9/30/92 Bill Haake & Peter Lennie modified the code for the 8x24 card
  386. and the 8x24GC to make it a) work properly in 32-bit mode. b) to fix a bug
  387. (feature?) of the original drivers that prevented the cards running on a Quadra.
  388. The drivers exploit 'byte-smearing' on the 68020 and 68030 (Tech Note 282). This
  389. means that one can move a byte to the lowest byte address of the data register
  390. on the card, when one actually wants to put it at address+3 (!!). The functions
  391. work for all the cards (except toby, which hasn't been tested) and on internal
  392. video in both 24 and 32 bit mode on Quadra 700/950, IIfx or ci running system
  393. 7.0.1.
  394.     
  395. 9/28/92 Peter Lennie added the function findcard.
  396.  
  397. 11/23/92 Denis Pelli (dgp) eliminated all globals because they implicitly
  398. assumed that there is only one video device. All routines now accept a GDHandle
  399. specifying which video device. Simplified the logic of GetCardBase(), minimizing
  400. the dependence on card type.
  401.  
  402. 11/25/92 dgp When USE_MSB is true, all the routines now use the most significant
  403. bits of the 16-bit elements of the user-supplied color tables. When it is false
  404. the least significant bits are used. This is mostly implemented by offseting the
  405. table pointers by one byte and only reading the desired byte. •Generalized
  406. macltset() to work with tables that have an arbitrary element spacing. This
  407. allows it to work with both with Raynald's convention of three arrays of shorts,
  408. and the Apple convention of a ColorSpec array, each element of which consists of
  409. red, green, blue, and value (which is not used). •Added alias "Toby frame buffer
  410. card" for tobycard.
  411.  
  412. 11/27/92 dgp Broke out the code for each card into separate subroutines. This
  413. allows optimal register assignment for each routine, and makes it much easier to read
  414. the THINK C disassembler output. The runtime overhead of loading and unloading
  415. the stack is negligible, and could be eliminated entirely by putting all the
  416. parameters in a structure and passing a pointer to it. •Added a flag,
  417. suspendInterrupts, to make interrupt suspension optional since it may be
  418. undesirable in some applications. (Blocking interrupts for 1 ms could cause you
  419. to miss the interrupt from a video card, especially if you are trying to keep
  420. track of interrupts on several video cards at once.)
  421.  
  422. 11/30/92 dgp Wrote TestCluts, which reads back the clut and checks all
  423. values, and used it to test SetEntriesQuickly() on Quadra 950 internal video,
  424. Mac IIci internal video, hirescard, "Toby frame buffer card", and 8•24 card at
  425. all depths, for both 24- and 32-bit addressing. Toby card was tested on 68020,
  426. 68030, and 68040 processors. •Wrote documentation. •Replaced compile-time constants
  427. USE_MSB and PRO_8BITS by runtime flags passed as arguments. •Added WaitForNextBlanking()
  428. based on code from VideoTFB.c.
  429.  
  430. 12/3/92 dgp Incorporated Peter Lennie's corrections and additions to the comments above.
  431.  
  432. 12/8/92 dgp Added missing "case" to switch in WaitForNextBlanking.
  433.  
  434. 12/13/92 dgp Changed erroneous "&d" to "%d" in a printf. Added some comments to
  435. the documentation above.
  436.             
  437. 12/15/92 dgp Now get mode from device record and leave it in standard form, 
  438. i.e. with the 0x80 bit set, and only strip off that bit when actually necessary,
  439. e.g. in LoadClutMacIIci. 
  440.  
  441. 12/30/92 dgp Make sure routines return zero when there's no error.
  442.  
  443. 2/15/93    dgp Rewrote nonworking LoadClutToby in C, and made it work. Rewrote
  444. nonworking LoadClutx824 in C, and made it work. Fixed sixteenBitMode in
  445. LoadClutQuadra. Use new SwapPriority instead of Get/SetPriority.
  446.  
  447. 2/20/93    dgp    Translated LoadClutGCx824 to C. (It was ignoring the start value.)
  448.  
  449. 3/4/93    dgp    Added macIIsi to list of supported cards, since it uses the same
  450. driver as the Mac IIci. Changed definitions of string types slightly to allow
  451. compilation of this file as a code resource. However, the assembly code
  452. uses more registers than are available to a code resource.
  453.  
  454. 4/13/93    dgp    Removed 68020 requirement by translating an indexed add in LoadMacIIci to
  455. C.
  456.  
  457. 4/17/93 dgp Added support in GetCardBase for old Mac II computers whose ROM's only 
  458. support 24-bit NuBus addressing. 
  459.  
  460. 5/18/93 SetEntriesQuickly now respects the setting of the device's gray/color mode, 
  461. and maps to gray if in the device is in gray mode and pixelSize<=8. Changed prototype
  462. of macltset to specify the red, green, and blue arrays as "unsigned short" instead of 
  463. "short".
  464.  
  465. 7/7/93    dgp    Disabled some global optimizations because THINK C 6 will
  466. crash while compiling if the Radius PowerView is present: "!gopt_induction,!gopt_loop".
  467.  
  468. 7/9/93    dgp check for 32-bit addressing capability.
  469.  
  470. 6/14/94    dgp    can32 is now computed by calling TrapAvailable(_SwapMMUMode), which 
  471. returns correct answer even on Macs with dirty ROMs.
  472.  
  473. 6/14/94    dgp    Added call to SwapMMUMode in LoadClutToby, because it seemed odd not to.
  474. LoadClutMacIIci still doesn't, because the video buffer is in memory.
  475.  
  476. 6/30/94 dgp Updated the documentation.
  477.  
  478. 7/27/94 dgp Moved the list of compatible devices from the "Video synch" document
  479. to here, at the top of the file.
  480.  
  481. 7/29/94 dgp Made use of the asm directive conditional on THINK_C, for compatibility
  482. with other compilers. Changed LoadClutx824GC() to use its C instead of its asm code. 
  483. However, I don't know if the C code has been tested. GetCardType() returns nonzero
  484. only if the card is supported by the compiled code (i.e. ProColor, Quadra, and Mac
  485. IIci and IIsi are recognized only if this file is compiled by THINK C.)
  486.  
  487. 1/13/95 dgp Added information, above, from Rhea Eskew about the RasterOps 8L.
  488.  
  489. 1/16/95 dgp Added information, above, from Ben Singer about the Quadra 840AV & 660AV.
  490. Added LoadClutQuadraAV() based on Ben's code.
  491.  
  492. 5/23/95 dgp Apple changed the prototype in the header file from SwapMMUMode(char *) to 
  493.             SwapMMUMode(signed char *). To retain compatibility with both old and new
  494.             headers, I cast the argument (void *).
  495. 8/15/95 dgp changed style of definition of internalVideoBase for compatibility with
  496.          Symantec C++. Bug reported by Bosco.
  497. */
  498. #include "VideoToolbox.h"
  499. #define _SwapMMUMode 0xA05D
  500. #define USE_ONLY_8_BITS_IN_MACLTSET 0    // 1 to use RasterOps ProColor32 as an 8-bit DAC.
  501. #if (THINK_C || THINK_CPLUS || SYMANTEC_C)
  502.     #pragma options(assign_registers,honor_register,redundant_loads,defer_adjust)
  503.     #pragma options(global_optimizer,!gopt_induction,!gopt_loop,gopt_cse,gopt_coloring)
  504. #endif
  505.  
  506. // These are the five user-callable routines:
  507. OSErr WaitForNextBlanking(GDHandle device);
  508. OSErr SetEntriesQuickly(GDHandle device,short start,short count,ColorSpec *table);
  509. short macltset(GDHandle device,short start
  510.     ,unsigned short* red,unsigned short* green,unsigned short* blue,short count1);
  511. short GetCardType(GDHandle device);
  512. char *GetCardBase(GDHandle device);
  513.  
  514. /*
  515. I suggest keeping the following information private to this file. In principle
  516. you could publish these card types and use them in your programs. However, in
  517. practice, I cannot see any point in doing so. If you need to identify the card
  518. name I suggest you simply use the string returned by GDCardName(device) in
  519. GDVideo.c of the VideoToolbox. (Don't forget to call DisposPtr() when you're
  520. through with the string.) Or use GDName(device), which returns the name of the
  521. card's driver, and is much quicker. If you simply want to know whether your
  522. video card is supported by SetEntriesQuickly.c then you can simply make sure
  523. that GetCardType() returns a nonzero cardType.
  524. */
  525. struct vtype {        /* associates card name and id */
  526.     char name[40];
  527.     short id;
  528. };
  529. enum {                /* card identifiers */
  530.     tobycard = 1,
  531.     hirescard,
  532.     macIIci,
  533.     macIIsi,
  534.     x824card,
  535.     x824GCcard,
  536.     quadra700,
  537.     quadra900,
  538.     quadra950,
  539.     procolor32,
  540.     quadra660 = 0x50, /* quadra 660AV internal video */
  541.     quadra840 = 0x3D /* quadra 840AV internal video */
  542. };
  543.  
  544. static struct vtype card[] = {    // card name & id        // Original author:
  545.     {"Toby frame buffer card",                tobycard},    // Raynald Comtois
  546.     {"Display_Video_Apple_TFB",                tobycard},    //     "      "
  547.     {"Mac II High-Resolution Video Card",    hirescard},    // Raynald Comtois
  548.     {"Macintosh Display Card",                x824card},    // Raynald Comtois
  549.     {"Macintosh Display Card 8•24 GC",        x824GCcard},// Raynald Comtois
  550.     #if THINK_C    // the asm directive is supported only by THINK C
  551.         {"Macintosh II Built-In Video",            macIIci},    // Raynald Comtois
  552.         {"Macintosh A Built-In Video",            macIIsi},    //     "      "
  553.         {"Macintosh E Built-In Video",            quadra700},    // Peter Lennie
  554.         {"Macintosh C Built-In Video",            quadra900},    //     "      "
  555.         {"Macintosh G Built-In Video",            quadra950},    //     "      "
  556.         {"Macintosh 3A",                        quadra840},    // Ben Singer
  557.         {"Macintosh 3B",                        quadra660},    // Ben Singer
  558.         {"ProColor 32",                            procolor32}    // Bill Haake
  559.     #endif
  560. };
  561. static char driverName[][40]=        // Not used at present.
  562. {
  563.     "\p.Display_Video_Apple_TFB"    // Apple “Toby frame buffer card”
  564.     ,"\p.Display_Video_Apple_HRVC"    // Apple “Mac II High-Resolution Video Card”
  565.     ,"\p.Display_Video_Apple_MDC"    // Apple 8•24 “Macintosh Display Card”
  566.     ,"\p.Display_Video_Apple_MDCGC"    // Apple 8•24GC
  567.     ,"\p.Display_Video_Apple_RBV1"    // Mac IIci and IIsi built-in video
  568.     ,"\p.Display_Video_Apple_DAFB"    // Quadra 700, 900, 950 built-in video
  569.     ,"\p.Display_Video_Apple_Civic"    // Quadra 640AV, 840AV built-in video
  570.     ,"\p.RasterOps 1.0 32XL Video Driver"    // Radius ProColor 32
  571. };
  572. enum {                            // Flags passed to LoadClut().
  573.     suspendInterrupts=1,
  574.     useMostSignificantBits=2,
  575.     useOnly8Bits=4,
  576.     waitForNextBlanking=8
  577. };
  578. enum{quadraNonzeroStart=111};    // value returned as error.
  579.     
  580. short LoadClut(GDHandle device,short start,short count
  581.     ,unsigned short* red,unsigned short* green,unsigned short* blue,long elementSpacing,short flags);
  582. OSErr LoadClutProColor(short start,short count,char *r,char *g,char *b
  583.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  584.     ,char *cardBase,short flags);
  585. OSErr LoadClutQuadraAV(short start,short count,char *r,char *g,char *b
  586.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  587.     ,char *cardBase,short flags);
  588. OSErr LoadClutQuadra(short start,short count,char *r,char *g,char *b
  589.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  590.     ,char *cardBase,short flags);
  591. OSErr LoadClutMacIIci(short start,short count,char *r,char *g,char *b
  592.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  593.     ,char *cardBase,short flags);
  594. OSErr LoadClutHiRes(short start,short count,char *r,char *g,char *b
  595.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  596.     ,char *cardBase,short flags);
  597. OSErr LoadClutx824(short start,short count,char *r,char *g,char *b
  598.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  599.     ,char *cardBase,short flags);
  600. OSErr LoadClutx824GC(short start,short count,char *r,char *g,char *b
  601.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  602.     ,char *cardBase,short flags);
  603. OSErr LoadClutToby(short start,short count,char *r,char *g,char *b
  604.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  605.     ,char *cardBase,short flags);
  606. /******************************************************************************/
  607. /*
  608. The arguments start, count, and table are the same as for the Color Manager call
  609. SetEntries(), documented in Inside Macintosh V-143. (Except that a count==-1 is
  610. considered illegal here.) Apple's ideosyncratic convention is that "count" is
  611. "zero-based", meaning that it is one less than the number of clut entries that
  612. you want to modify. "count" must be at least zero. Returns zero if successful,
  613. nonzero if unsuccessful, i.e. illegal arguments.
  614. */
  615. OSErr SetEntriesQuickly(GDHandle device,short start,short count,ColorSpec *table)
  616. {
  617.     short flags=useMostSignificantBits;
  618.     //flags+=suspendInterrupts;        // Optional, no
  619.     //flags+=waitForNextBlanking;    // Optional, no
  620.  
  621.     return LoadClut(device,start,count
  622.         ,&table[0].rgb.red,&table[0].rgb.green
  623.         ,&table[0].rgb.blue,sizeof(table[0]),flags);
  624. }
  625. /******************************************************************************/
  626. short macltset(GDHandle device,register short start
  627.     ,unsigned short* red,unsigned short* green,unsigned short* blue,short count1)
  628. {
  629.     short flags=0;
  630.     flags+=suspendInterrupts;        // Optional
  631.     #if USE_ONLY_8_BITS_IN_MACLTSET
  632.         flags+=useOnly8Bits;        // Optional
  633.     #endif
  634.     //flags+=waitForNextBlanking;    // Optional
  635.     
  636.     return LoadClut(device,start,count1-1,red,green,blue,sizeof(red[0]),flags);
  637. }
  638. /******************************************************************************/
  639. /*
  640. The first call to GetCardType for a particular device takes 1.5-3 ms, depending
  641. on your computer's speed, because it takes Apple's Slot Manager a long time to
  642. get the card name. However, GetCardType's answers are cached so subsequent calls
  643. for a previously queried device will be fast <100 µs.
  644. */
  645. short GetCardType(GDHandle device)    // returns card type, if known, or zero if not.
  646. {
  647.     register short i;
  648.     short cardType;
  649.     char *name;
  650.     static GDHandle deviceCache[MAX_SCREENS];
  651.     static short typeCache[MAX_SCREENS];
  652.     
  653.     // Do we already know the answer? Check the cache.
  654.     for(i=0;i<MAX_SCREENS;i++)if(device==deviceCache[i])return typeCache[i];
  655.     // Get card name, see if it's in our list of known cards
  656.     name=GDCardName(device);
  657.     cardType=0;
  658.     for (i=0; i<sizeof(card)/sizeof(card[0]); i++){
  659.         if(strcmp(name,card[i].name)==0){
  660.             cardType=card[i].id;
  661.             break;
  662.         }
  663.     }
  664.     DisposePtr(name);
  665.     // Save answer in cache.
  666.     for(i=0;i<MAX_SCREENS;i++)if(deviceCache[i]==0){
  667.         typeCache[i]=cardType;
  668.         deviceCache[i]=device;
  669.         break;
  670.     }
  671.     return cardType;
  672. }
  673. /******************************************************************************/
  674. //long internalVideoBase:0xDD8;    // Undocumented System global
  675. #define internalVideoBase (*((long *)0xDD8))
  676.  
  677. char *GetCardBase(GDHandle device)
  678. {
  679.     long cardBase,slot;    /* slot must be declared long */
  680.     short cardType;
  681.     
  682.     slot=GetDeviceSlot(device);
  683.     cardType=GetCardType(device);
  684.     if(slot==0){
  685.         // Built-in video, not in a NuBus slot.
  686.         switch(cardType){
  687.         case quadra660:
  688.         case quadra840:
  689.             #if 1
  690.                 // This C statement is equivalent to Ben Singer's assembly code below.
  691.                 cardBase = *(long *)(internalVideoBase + *(long *)internalVideoBase + 164);
  692.             #else
  693.                 asm {
  694.                     move.l 0xDD8,a0        /* internal video 040 AV's */
  695.                     adda.l (a0),a0
  696.                     move.l 164(a0),a1
  697.                     move.l a1,cardBase
  698.                 }
  699.             #endif
  700.             break;
  701.         default:
  702.             // E.g.: macIIci,macIIsi,quadra700,quadra900,quadra950
  703.             #if 1
  704.                 // This C is equivalent to Raynald's assembly code below.
  705.                 cardBase = *(long *)(internalVideoBase + *(long *)internalVideoBase + 56);
  706.             #else
  707.                 asm {
  708.                     move.l 0xDD8,a0        /* get card base address */
  709.                     adda.l (a0),a0
  710.                     move.l 56(a0),a1
  711.                     move.l a1,cardBase
  712.                 }
  713.             #endif
  714.             break;
  715.         }
  716.     }else{
  717.         // Video card in NuBus slot
  718.         switch(cardType){
  719.             case x824GCcard:
  720.                 cardBase = slot<<28;    // a superslot
  721.                 break;
  722.             case tobycard:
  723.             case hirescard:
  724.                 cardBase = (slot<<24) | 0xF0000000;
  725.                 cardBase+= (slot<<20);    // Support old Mac II 24-bit NuBus addressing
  726.                 break;
  727.             case procolor32:             // RasterOps
  728.             case x824card:
  729.             default:
  730.                 cardBase = (slot<<24) | 0xF0000000;
  731.                 break;
  732.         }
  733.     }
  734.     return (char *)cardBase;
  735. }
  736. /******************************************************************************/
  737. short LoadClut(GDHandle device,short start,short count
  738.     ,unsigned short* red,unsigned short* green,unsigned short* blue
  739.     ,long elementSpacing,short flags)
  740. {
  741.     char *cardBase;
  742.     short cardType=0,pixelSize,mode;
  743.     short clutSize;     // entries in the lookup table
  744.     int error,i,j;
  745.     short isGray;
  746.     unsigned short grayTable[256];
  747.     
  748.     if(device==NULL)return 1;
  749.     cardType=GetCardType(device);    // takes 1.7 ms the first time for each device.
  750.     if(cardType==0)return 1;
  751.     cardBase=GetCardBase(device);
  752.     clutSize=GDClutSize(device);
  753.     pixelSize=(**(**device).gdPMap).pixelSize;
  754.     mode=(**device).gdMode;
  755.     
  756.     // Check range.
  757.     if(start>clutSize-1 || start<0 || count+start>clutSize-1 || count<0)return 1;
  758.     
  759.     // We're going to use these RAM addresses in 32-bit mode.
  760.     red = (unsigned short *)StripAddress(red);
  761.     green = (unsigned short *)StripAddress(green);
  762.     blue = (unsigned short *)StripAddress(blue);
  763.  
  764.     if(waitForNextBlanking & flags){
  765.         WaitForNextBlanking(device);
  766.     }
  767.     
  768.     isGray=!TestDeviceAttribute(device,gdDevType);
  769.     if(isGray && pixelSize<=8){
  770.         j=elementSpacing/sizeof(*red);
  771.         for(i=0;i<=count;i++){
  772.             grayTable[i]=*red*0.30+*green*0.59+*blue*0.11;
  773.             red+=j;
  774.             green+=j;
  775.             blue+=j;
  776.         }
  777.         elementSpacing=sizeof(grayTable[0]);
  778.         red=green=blue=grayTable;
  779.     }
  780.     
  781.     // After the above setting up, actually loading 256x3 clut entries takes <2 ms.
  782.     switch (cardType) {
  783.         // I packaged the code for each case into a separate subroutine
  784.         // in order to allow the THINK C compiler to optimize each
  785.         // one independently. An important consideration is that the THINK C 5.04
  786.         // compiler disables most optimizations for any function that includes
  787.         // the "asm" directive anywhere within the function. Thus mixing C and assembly
  788.         // will result in inefficient C. No less important, the THINK C Disassemble
  789.         // command is very handy in writing fast C code, but produces an uncommented 
  790.         // listing, which is much easier to read if the separate routines are each 
  791.         // named subroutines.
  792.         case procolor32:
  793.             error=LoadClutProColor(start,count,(char *)red,(char *)green,(char *)blue,
  794.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  795.             break;
  796.         case quadra660:
  797.         case quadra840:
  798.             error=LoadClutQuadraAV(start,count,(char *)red,(char *)green,(char *)blue,
  799.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  800.             break;
  801.         case quadra700:
  802.         case quadra900:
  803.         case quadra950:
  804.             error=LoadClutQuadra(start,count,(char *)red,(char *)green,(char *)blue,
  805.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  806.             break;
  807.         case macIIci:
  808.         case macIIsi:
  809.             error=LoadClutMacIIci(start,count,(char *)red,(char *)green,(char *)blue,
  810.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  811.             break;
  812.         case hirescard:
  813.             error=LoadClutHiRes(start,count,(char *)red,(char *)green,(char *)blue,
  814.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  815.             break;
  816.         case x824card:
  817.             error=LoadClutx824(start,count,(char *)red,(char *)green,(char *)blue,
  818.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  819.             break;
  820.         case x824GCcard:
  821.             error=LoadClutx824GC(start,count,(char *)red,(char *)green,(char *)blue,
  822.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  823.             break;
  824.         case tobycard:
  825.             error=LoadClutToby(start,count,(char *)red,(char *)green,(char *)blue,
  826.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  827.             break;
  828.     }
  829.     return error;
  830. }
  831. /******************************************************************************/
  832. OSErr LoadClutProColor(short start,register short count
  833.     ,register char *red,register char *green,register char *blue
  834.     ,register long elementSpacing
  835.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  836. {
  837. #if THINK_C
  838.     signed char mmuMode=true32b;
  839.     char priority=7;
  840.     register long bitShift;
  841.     static Boolean can32,firstTime=1;
  842.  
  843.     if(firstTime){
  844.         can32=TrapAvailable(_SwapMMUMode);
  845.         firstTime=0;
  846.     }
  847.     if(useMostSignificantBits & flags){
  848.         bitShift=9;
  849.     }else{
  850.         if(useOnly8Bits & flags) bitShift=1;
  851.         else bitShift=0;
  852.     }
  853.     if(suspendInterrupts & flags)SwapPriority(&priority);
  854.     if(can32)SwapMMUMode((void *)&mmuMode);
  855.     asm {
  856.         move.l cardBase,a1        /* get card base address */
  857.         adda.l    #0xf60000,a1    /* offset to control registers */        
  858.     @9    move.w    start,2(a1)        /* Set the index on the card */
  859.         move.w (red),d1
  860.         add.l elementSpacing,red
  861.         lsl.w bitShift,d1
  862.         move.w d1,14(a1)
  863.         move.w (green),d1
  864.         add.l elementSpacing,green
  865.         lsl.w bitShift,d1
  866.         move.w d1,14(a1)
  867.         move.w (blue),d1
  868.         add.l elementSpacing,blue
  869.         lsl.w bitShift,d1
  870.         move.w d1,14(a1)
  871.         addq.w    #1,start        /* Point to next entry in table */
  872.         dbf count,@9
  873.     }
  874.     if(can32)SwapMMUMode((void *)&mmuMode);
  875.     if(suspendInterrupts & flags)SwapPriority(&priority);
  876.     return 0;
  877. #else
  878.     start;count;red;green;blue;elementSpacing;mode;pixelSize;clutSize;cardBase;flags;    // prevent "unused argument" warning
  879.     return 1;
  880. #endif
  881. }
  882. /*
  883. Ben Singer writes, 
  884. "I've tested this on both the 660AV and 840AV, but only in 8-bit ("256
  885. colors";count=256) mode. As with other quadra internal video code, this doesn't
  886. incorporate the "start" parameter. Thanks to Peter Lennie. Thanks also to you
  887. for GrabDriver and the tip on using the ResEdit CODE extension to examine the
  888. disassembly."
  889. dgp adds,
  890. I modified Ben's code to work within the conventions of SetEntriesQuickly. In
  891. particular Ben was using the low byte of the color spec, but Apple suggests
  892. using the high byte. 
  893. */
  894. OSErr LoadClutQuadraAV(short start,register short count
  895.     ,register char *red,register char *green,register char *blue
  896.     ,register long elementSpacing
  897.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  898. {
  899.     if(start!=0)return quadraNonzeroStart;    // code assumes start==0
  900.     if(pixelSize<8)return 1;                // code doesn't work for small pixels
  901.     #if THINK_C
  902.         asm {    // no _SwapMMUMode; 040 AV's always in 32-bit mode
  903.             move.l cardBase,a1  
  904.             lea 0x10(a1),a1    // offsets 0x10,0x110,0x210,0x310 work
  905.             clr.l -16(a1)
  906.             move sr,-(a7)
  907.             ori #0x700,sr    // disable interrupts
  908.             clr.l d1
  909.         @1    move.b (red),(a1)
  910.             add.l elementSpacing,red
  911.             move.b (green),(a1)
  912.             add.l elementSpacing,green
  913.             move.b (blue),(a1)
  914.             add.l elementSpacing,blue
  915.             clr.b (a1)
  916.             dbf count,@1
  917.             move (a7)+,sr    // enable interrupts
  918.         }
  919.     #else
  920.         // prevent "unused argument" warning
  921.         count; red; green; blue; elementSpacing; mode; pixelSize; clutSize; cardBase; flags;
  922.         return 1;
  923.     #endif
  924. }
  925. OSErr LoadClutQuadra(short start,register short count
  926.     ,register char *red,register char *green,register char *blue
  927.     ,register long elementSpacing
  928.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  929. {
  930. #if THINK_C
  931.     signed char mmuMode=true32b;
  932.     char priority=7;
  933.     static Boolean can32,firstTime=1;
  934.  
  935.     if(firstTime){
  936.         can32=TrapAvailable(_SwapMMUMode);
  937.         firstTime=0;
  938.     }
  939.     if(start!=0){
  940.         //printf("LoadClutQuadra: start must be zero\n");
  941.         return quadraNonzeroStart;
  942.     }
  943.     if(!(useMostSignificantBits & flags)){
  944.         // Point to less significant byte of word.
  945.         red++;
  946.         green++;
  947.         blue++;
  948.     }
  949.     if(suspendInterrupts & flags)SwapPriority(&priority);
  950.     if(can32)SwapMMUMode((void *)&mmuMode);
  951.     if(mode!=sixteenBitMode)asm{
  952.         move.l cardBase,a1
  953.         lea 0x210(a1), a1
  954.         clr.l -16(a1)
  955.     @4    move.b (red),d1
  956.         add.l elementSpacing,red
  957.         move.l d1,(a1)
  958.         move.b (green),d1
  959.         add.l elementSpacing,green
  960.         move.l d1,(a1)
  961.         move.b (blue),d1
  962.         add.l elementSpacing,blue
  963.         move.l d1,(a1)
  964.         dbf count,@4
  965.     }else asm{
  966.     // In sixteenBitMode the clut addressing is weird.
  967.     // I arrived at the following solution by trial and error.
  968.     // It's a kludge, but is still fast enough. dgp.
  969.         move.l cardBase,a1
  970.         lea 0x210(a1), a1
  971.         clr.l -16(a1)
  972.     @44    move.b (red),d1
  973.         move.l d1,(a1)
  974.         move.b (green),d1
  975.         move.l d1,(a1)
  976.         move.b (blue),d1
  977.         move.l d1,(a1)
  978.  
  979.         move.b (red),d1
  980.         move.l d1,(a1)
  981.         move.b (green),d1
  982.         move.l d1,(a1)
  983.         move.b (blue),d1
  984.         move.l d1,(a1)
  985.  
  986.         move.b (red),d1
  987.         move.l d1,(a1)
  988.         move.b (green),d1
  989.         move.l d1,(a1)
  990.         move.b (blue),d1
  991.         move.l d1,(a1)
  992.  
  993.         move.b (red),d1
  994.         move.l d1,(a1)
  995.         move.b (green),d1
  996.         move.l d1,(a1)
  997.         move.b (blue),d1
  998.         move.l d1,(a1)
  999.  
  1000.         move.b (red),d1
  1001.         move.l d1,(a1)
  1002.         move.b (green),d1
  1003.         move.l d1,(a1)
  1004.         move.b (blue),d1
  1005.         move.l d1,(a1)
  1006.  
  1007.         move.b (red),d1
  1008.         move.l d1,(a1)
  1009.         move.b (green),d1
  1010.         move.l d1,(a1)
  1011.         move.b (blue),d1
  1012.         move.l d1,(a1)
  1013.  
  1014.         move.b (red),d1
  1015.         move.l d1,(a1)
  1016.         move.b (green),d1
  1017.         move.l d1,(a1)
  1018.         move.b (blue),d1
  1019.         move.l d1,(a1)
  1020.  
  1021.         move.b (red),d1
  1022.         add.l elementSpacing,red
  1023.         move.l d1,(a1)
  1024.         move.b (green),d1
  1025.         add.l elementSpacing,green
  1026.         move.l d1,(a1)
  1027.         move.b (blue),d1
  1028.         add.l elementSpacing,blue
  1029.         move.l d1,(a1)
  1030.  
  1031.         dbf count,@44
  1032.     }
  1033.     if(can32)SwapMMUMode((void *)&mmuMode);
  1034.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1035.     return 0;
  1036. #else
  1037.     // prevent "unused argument" warning
  1038.     start;count;red;green;blue;elementSpacing;mode;pixelSize;clutSize;cardBase;flags;
  1039.     return 1;
  1040. #endif
  1041. }
  1042. OSErr LoadClutMacIIci(register short start,register short count
  1043.     ,register char *red,register char *green,register char *blue
  1044.     ,register long elementSpacing
  1045.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  1046. {
  1047. #if THINK_C
  1048.     static char realstartindex[] = {0xFE, 0xFC, 0xF0, 0x00,0,0,0};
  1049.     char priority=7;
  1050.     static Boolean can32,firstTime=1;
  1051.  
  1052.     if(firstTime){
  1053.         can32=TrapAvailable(_SwapMMUMode);
  1054.         firstTime=0;
  1055.     }
  1056.     if(!(useMostSignificantBits & flags)){
  1057.         // Point to less significant byte of word.
  1058.         red++;
  1059.         green++;
  1060.         blue++;
  1061.     }
  1062.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1063.     mode&=7;
  1064.     start+=realstartindex[mode];
  1065.     asm {
  1066.         move.w mode,d1
  1067.         move.l cardBase,a0        // get card base address
  1068.         move.l a0,a1
  1069. //        move.b #255,8(a0)        // not necessary
  1070.         move.b start,(a0)
  1071.         addq.l #4,a1
  1072.     @3    move.b (red),d1
  1073.         add.l elementSpacing,red
  1074.         move.b d1,(a1)
  1075.         move.b (green),d1
  1076.         add.l elementSpacing,green
  1077.         move.b d1,(a1)
  1078.         move.b (blue),d1
  1079.         add.l elementSpacing,blue
  1080.         move.b d1,(a1)
  1081.         dbf count,@3
  1082.     }
  1083.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1084.     return 0;
  1085. #else
  1086.     start;count;red;green;blue;elementSpacing;mode;pixelSize;clutSize;cardBase;flags;    // prevent "unused argument" warning
  1087.     return 1;
  1088. #endif
  1089. }
  1090. // High resolution video card
  1091. //#define HRVCBase            0x80000
  1092. #define HRVCClutAddrReg        0x940E0
  1093. #define HRVCClutWDataReg    0x940E4
  1094. //#define HRVCClutRDataReg    0x94054
  1095. OSErr LoadClutHiRes(short start,register short count
  1096.     ,register char *red,register char *green,register char *blue
  1097.     ,register long elementSpacing
  1098.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  1099. {
  1100.     char *bytePtr;
  1101.     signed char mmuMode=true32b;
  1102.     char priority=7;
  1103.     static Boolean can32,firstTime=1;
  1104.  
  1105.     mode;pixelSize;    // prevent "unused argument" warning
  1106.     if(firstTime){
  1107.         can32=TrapAvailable(_SwapMMUMode);
  1108.         firstTime=0;
  1109.     }
  1110.     if(!(useMostSignificantBits & flags)){
  1111.         // Point to less significant byte of word.
  1112.         red++;
  1113.         green++;
  1114.         blue++;
  1115.     }
  1116.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1117.     if(can32)SwapMMUMode((void *)&mmuMode);
  1118.     red+=count*elementSpacing;
  1119.     green+=count*elementSpacing;
  1120.     blue+=count*elementSpacing;
  1121.     // We'll start with clut entry start+count, and work
  1122.     // down from there to clut entry start. The clut address
  1123.     // register counts down automatically.
  1124.     *(cardBase+HRVCClutAddrReg)=~(clutSize-1-start-count);
  1125.     bytePtr=cardBase+HRVCClutWDataReg;
  1126.     // This is the key loop. 
  1127.     // This C code is only about 10% slower than the original assembly code.
  1128.     elementSpacing= -elementSpacing;
  1129.     do{
  1130.         *bytePtr=~ *red;
  1131.         red+=elementSpacing;
  1132.         *bytePtr=~ *green;
  1133.         green+=elementSpacing;
  1134.         *bytePtr=~ *blue;
  1135.         blue+=elementSpacing;
  1136.     }while(--count>=0);
  1137.     if(can32)SwapMMUMode((void *)&mmuMode);
  1138.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1139.     return 0;
  1140. }
  1141. // Macintosh display card (8•24)
  1142. //#define MDCVideoBase        0xA00
  1143. #define MDCClutAddrReg        0x200200
  1144. #define MDCClutDataReg        0x200204
  1145. OSErr LoadClutx824(short start,register short count
  1146.     ,register char *red,register char *green,register char *blue
  1147.     ,register long elementSpacing
  1148.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  1149. {
  1150.     signed char mmuMode=true32b;
  1151.     char priority=7;
  1152.     register char *clut;
  1153.     char *clutIndex;
  1154.     static Boolean can32,firstTime=1;
  1155.  
  1156.     mode;pixelSize;clutSize;    // prevent "unused argument" warning
  1157.     if(firstTime){
  1158.         can32=TrapAvailable(_SwapMMUMode);
  1159.         firstTime=0;
  1160.     }
  1161.     if(!(useMostSignificantBits & flags)){
  1162.         // Point to less significant byte of word.
  1163.         red++;
  1164.         green++;
  1165.         blue++;
  1166.     }
  1167.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1168.     if(can32)SwapMMUMode((void *)&mmuMode);
  1169.     clut=cardBase+MDCClutDataReg+3;
  1170.     clutIndex=cardBase+MDCClutAddrReg;
  1171.     *clutIndex=start;
  1172.     for(;count>=0;count--){
  1173.         *clut=*red;
  1174.         red+=elementSpacing;
  1175.         *clut=*green;
  1176.         green+=elementSpacing;
  1177.         *clut=*blue;
  1178.         blue+=elementSpacing;
  1179.     }
  1180.     if(can32)SwapMMUMode((void *)&mmuMode);
  1181.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1182.     return 0;
  1183. }
  1184. // Macintosh display card 8•24 GC
  1185. #define MDCgcClutAddrReg    0x6C00000
  1186. #define MDCgcClutDataReg    0x6C00004
  1187. OSErr LoadClutx824GC(short start,register short count
  1188.     ,register char *red,register char *green,register char *blue
  1189.     ,register long elementSpacing
  1190.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  1191. {
  1192.     signed char mmuMode=true32b;
  1193.     char priority=7;
  1194.     register long *clut;
  1195.     char *clutIndex;
  1196.     static Boolean can32,firstTime=1;
  1197.  
  1198.     mode;pixelSize;clutSize;    // prevent "unused argument" warning
  1199.     if(firstTime){
  1200.         can32=TrapAvailable(_SwapMMUMode);
  1201.         firstTime=0;
  1202.     }
  1203.     if(!(useMostSignificantBits & flags)){
  1204.         // Point to less significant byte of word.
  1205.         red++;
  1206.         green++;
  1207.         blue++;
  1208.     }
  1209.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1210.     if(can32)SwapMMUMode((void *)&mmuMode);
  1211.     clutIndex=cardBase+MDCgcClutAddrReg;
  1212.     *clutIndex=start;
  1213.     #if 1
  1214.         clut=(long *)(cardBase+MDCgcClutDataReg);
  1215.         for(;count>=0;count--){
  1216.             *clut=(long)(*red)<<24;
  1217.             red+=elementSpacing;
  1218.             *clut=(long)(*green)<<24;
  1219.             green+=elementSpacing;
  1220.             *clut=(long)(*blue)<<24;
  1221.             blue+=elementSpacing;
  1222.         }
  1223.     #else
  1224.         asm {
  1225.             move.l cardBase,a1
  1226.             add.l #MDCgcClutDataReg,a1
  1227.         @8    move.b (red),d1
  1228.             add.l    elementSpacing,red
  1229.             ror.l    #8,d1
  1230.             move.l d1,(a1)
  1231.             move.b (green),d1
  1232.             add.l    elementSpacing,green
  1233.             ror.l    #8,d1
  1234.             move.l d1,(a1)
  1235.             move.b (blue),d1
  1236.             add.l elementSpacing,blue
  1237.             ror.l    #8,d1
  1238.             move.l d1,(a1)
  1239.             dbf count,@8
  1240.         }
  1241.     #endif
  1242.     if(can32)SwapMMUMode((void *)&mmuMode);
  1243.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1244.     return 0;
  1245. }
  1246. // Toby frame buffer
  1247. //#define    TFBBase            0x80000
  1248. //#define TFBBufMid            0x80008
  1249. //#define TFBBufLow            0x8000C
  1250. //#define    TFBIBase        0x8fffc
  1251. #define TFBClutWDataReg        0x90018
  1252. //#define TFBClutRDataReg    0x90028
  1253. #define TFBClutAddrReg        0x9001C
  1254. #define    TFBReadVSync        0xD0000
  1255. //#define    TFBReadVInt        0xD0004
  1256. //#define    TFBReadIntlc    0xD0008
  1257. //#define    TFBVIntEnable    0xA0000
  1258. //#define    TFBVIntDisable    0xA0004
  1259. OSErr LoadClutToby(short start,register short count
  1260.     ,register char *red,register char *green,register char *blue
  1261.     ,register long elementSpacing
  1262.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  1263. {
  1264.     register long index;
  1265.     signed char mmuMode=true32b;
  1266.     char priority=7;
  1267.     register char *clut,*clutIndex;
  1268.     short shift;
  1269.     static Boolean can32,firstTime=1;
  1270.  
  1271.     mode;clutSize;    // prevent "unused argument" warning
  1272.     if(firstTime){
  1273.         can32=TrapAvailable(_SwapMMUMode);
  1274.         firstTime=0;
  1275.     }
  1276.     if(!(useMostSignificantBits & flags)){
  1277.         // Point to less significant byte of word.
  1278.         red++;
  1279.         green++;
  1280.         blue++;
  1281.     }
  1282.     index=(count+1)*elementSpacing;
  1283.     red+=index;
  1284.     green+=index;
  1285.     blue+=index;
  1286.     shift=8-pixelSize;
  1287.     index=start+count+1;
  1288.     clut=cardBase+TFBClutWDataReg;
  1289.     clutIndex=cardBase+TFBClutAddrReg;
  1290.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1291.     if(can32)SwapMMUMode((void *)&mmuMode);
  1292.     for(;count>=0;count--,index--){
  1293.         *clutIndex=(index<<shift)-1;
  1294.         red-=elementSpacing;
  1295.         *clut=~*red;
  1296.         green-=elementSpacing;
  1297.         *clut=~*green;
  1298.         blue-=elementSpacing;
  1299.         *clut=~*blue;
  1300.     }
  1301.     if(can32)SwapMMUMode((void *)&mmuMode);
  1302.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1303.     return 0;
  1304. }
  1305.  
  1306. OSErr WaitForNextBlanking(GDHandle device)
  1307. // WaitForNextBlanking waits for the beginning of the next vertical blanking interval.
  1308. // Returns 0 if successful, or 1 if device is not supported.
  1309. {
  1310.     register long *blankingPtr;
  1311.  
  1312.     switch(GetCardType(device)){
  1313.     case tobycard:
  1314.         blankingPtr = (long *) ((char *)GetCardBase(device) + TFBReadVSync);
  1315.         while (*blankingPtr & 1L) ;    // if we're already blanking, wait till end.
  1316.         while (!(*blankingPtr & 1L)) ; // wait until beginning of blanking interval.
  1317.         return 0;
  1318.     default:
  1319.         return 1;
  1320.     }
  1321. }
  1322.